document.addEventListener("DOMContentLoaded", () => {
  // --- DOM Elements ---
  const mazeGrid = document.getElementById("maze-grid");
  const playerElement = document.getElementById("player"); // Ensure this element exists in HTML
  const timerElement = document.getElementById("timer");
  const levelContainer = document.getElementById("level-container");
  const resetButton = document.getElementById("reset-button");
  const messageElement = document.getElementById("message");
  const fireworksCanvas = document.getElementById("fireworks-canvas"); // Needed for fireworks
  const mazeGridContainer = document.getElementById("maze-grid-container");
  const soundToggle = document.getElementById("sound-toggle");

  // --- Sound Elements ---
  const moveSound = document.getElementById("move-sound");
  const winSound = document.getElementById("win-sound");
  const resetSound = document.getElementById("reset-sound");
  const blockedSound = document.getElementById("blocked-sound");

  // --- Game State ---
  let maze = [];
  let playerPos = { x: 0, y: 0 };
  let startPos = { x: 0, y: 0 };
  let endPos = { x: 0, y: 0 };
  let rows = 0;
  let cols = 0;
  let cellSize = 30;
  let timerInterval = null;
  let startTime = 0;
  let gameActive = false;
  let firstMove = true;
  let currentLevel = 1;
  let soundEnabled = true;

  // --- Constants ---
  const WALL = 1;
  const PATH = 0;
  const START = 2;
  const END = 3;
  const MIN_MAZE_SIZE = 7;
  const LEVEL_INCREMENT = 1;
  const MAX_LEVEL = 30;

  // --- Create Level Buttons ---
  function createLevelButtons() {
    levelContainer.innerHTML = "";
    for (let i = 1; i <= MAX_LEVEL; i++) {
      const button = document.createElement("button");
      button.classList.add("level-button");
      button.textContent = i;
      button.dataset.level = i;
      if (i === currentLevel) {
        button.classList.add("active");
      }
      button.addEventListener("click", (e) => {
        const level = parseInt(e.target.dataset.level);
        if (level !== currentLevel) {
          currentLevel = level;
          playSound(resetSound);
          document.querySelectorAll(".level-button").forEach((btn) => {
            btn.classList.remove("active");
          });
          e.target.classList.add("active");
          initGame();
        }
      });
      levelContainer.appendChild(button);
    }
  }

  // --- Sound Control ---
  function playSound(sound) {
    if (soundEnabled && sound) {
      sound.currentTime = 0;
      sound.play().catch((err) => console.log("声音播放失败:", err));
    }
  }

  function toggleSound() {
    soundEnabled = !soundEnabled;
    soundToggle.querySelector("i").className = soundEnabled
      ? "fas fa-volume-up"
      : "fas fa-volume-mute";
    soundToggle.classList.toggle("muted", !soundEnabled);
  }

  // --- Maze Generation (No changes) ---
  function generateMaze(r, c) {
    // ... (code remains the same)
    rows = r % 2 === 0 ? r + 1 : r;
    cols = c % 2 === 0 ? c + 1 : c;
    maze = Array.from({ length: rows }, () => Array(cols).fill(WALL));
    const stack = [];
    const startX = 1;
    const startY = 1;
    maze[startY][startX] = PATH;
    stack.push([startX, startY]);
    while (stack.length > 0) {
      const [cx, cy] = stack[stack.length - 1];
      const neighbors = [];
      const directions = [
        [0, -2],
        [0, 2],
        [-2, 0],
        [2, 0],
      ];
      for (let i = directions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [directions[i], directions[j]] = [directions[j], directions[i]];
      }
      for (const [dx, dy] of directions) {
        const nx = cx + dx;
        const ny = cy + dy;
        if (
          nx > 0 &&
          nx < cols - 1 &&
          ny > 0 &&
          ny < rows - 1 &&
          maze[ny][nx] === WALL
        ) {
          neighbors.push([nx, ny, dx, dy]);
        }
      }
      if (neighbors.length > 0) {
        const [nx, ny, dx, dy] =
          neighbors[Math.floor(Math.random() * neighbors.length)];
        const wallX = cx + dx / 2;
        const wallY = cy + dy / 2;
        maze[wallY][wallX] = PATH;
        maze[ny][nx] = PATH;
        stack.push([nx, ny]);
      } else {
        stack.pop();
      }
    }
    startPos = { x: 1, y: 1 };
    endPos = { x: cols - 2, y: rows - 2 };
    if (maze[startPos.y][startPos.x] === WALL)
      maze[startPos.y][startPos.x] = PATH;
    if (maze[endPos.y][endPos.x] === WALL) maze[endPos.y][endPos.x] = PATH;
    maze[startPos.y][startPos.x] = START;
    maze[endPos.y][endPos.x] = END;
  }

  // --- Render Maze ---
  function renderMaze() {
    console.log("Rendering maze...");
    mazeGrid.innerHTML = ""; // Clear previous grid content
    messageElement.textContent = "";

    // *** UPDATED: Call clearFireworks here ***
    if (typeof clearFireworks === "function") {
      clearFireworks(); // Clear fireworks canvas on new level/reset
    } else {
      console.warn("clearFireworks function not found.");
    }

    // Get available space
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    // Calculate maze-area available width and height
    const controlsHeight = document.getElementById("controls").offsetHeight;
    const availableHeight = windowHeight - controlsHeight - 80; // Subtract margin and padding

    // Calculate container dimensions, considering fireworks-canvas space
    const containerWidth = Math.min(windowWidth * 0.9, 1400) - 220; // Subtract fireworks width and margin
    const containerHeight = availableHeight * 0.95;

    // Calculate cell size, ensuring maze fits container
    const maxCellWidth = Math.floor(containerWidth / cols);
    const maxCellHeight = Math.floor(containerHeight / rows);

    // Calculate best cell size, ensuring better display
    cellSize = Math.max(20, Math.min(maxCellWidth, maxCellHeight, 60));

    // If maze is too small, increase cellSize to fill more space
    if (
      cols * cellSize < containerWidth * 0.7 &&
      rows * cellSize < containerHeight * 0.7
    ) {
      const scaleFactorW = (containerWidth * 0.8) / (cols * cellSize);
      const scaleFactorH = (containerHeight * 0.8) / (rows * cellSize);
      const scaleFactor = Math.min(scaleFactorW, scaleFactorH, 1.5); // Limit max scale
      cellSize = Math.floor(cellSize * scaleFactor);
    }

    const gridWidth = cols * cellSize;
    const gridHeight = rows * cellSize;

    // Set maze grid dimensions
    mazeGrid.style.width = `${gridWidth}px`;
    mazeGrid.style.height = `${gridHeight}px`;
    mazeGrid.style.gridTemplateColumns = `repeat(${cols}, ${cellSize}px)`;
    mazeGrid.style.gridTemplateRows = `repeat(${rows}, ${cellSize}px)`;

    // Adjust maze container size
    mazeGridContainer.style.width = `${gridWidth + 10}px`; // Add padding
    mazeGridContainer.style.height = `${gridHeight + 10}px`;

    // Adjust fireworks canvas size
    if (fireworksCanvas) {
      fireworksCanvas.height = gridHeight > 0 ? gridHeight : 300;
      let fwWidth = parseInt(window.getComputedStyle(fireworksCanvas).width);
      fireworksCanvas.width = fwWidth > 0 ? fwWidth : 200;
    }

    // --- Create Cells ---
    for (let y = 0; y < rows; y++) {
      for (let x = 0; x < cols; x++) {
        const cell = document.createElement("div");
        cell.classList.add("cell");
        cell.style.width = `${cellSize}px`;
        cell.style.height = `${cellSize}px`;
        switch (maze[y][x]) {
          case WALL:
            cell.classList.add("wall");
            break;
          case PATH:
            cell.classList.add("path");
            break;
          case START:
            cell.classList.add("start");
            break;
          case END:
            cell.classList.add("end");
            cell.innerHTML = "🏠";
            cell.style.fontSize = `${Math.max(12, cellSize * 0.6)}px`;
            break;
        }
        mazeGrid.appendChild(cell);
      }
    }

    // --- Position Player ---
    playerPos = { ...startPos };
    if (!playerElement) {
      console.error("Player element not found!");
      return; // Stop if player element doesn't exist
    }
    playerElement.style.width = `${cellSize}px`;
    playerElement.style.height = `${cellSize}px`;
    playerElement.style.backgroundSize = `${Math.max(16, cellSize * 0.8)}px`;
    playerElement.style.backgroundPosition = "center";

    // *** UPDATED: Ensure player is appended correctly ***
    // Append player to the grid AFTER setting its size/styles
    // Check if it's already there to avoid issues on subsequent renders (though innerHTML clear should handle this)
    if (!mazeGrid.contains(playerElement)) {
      mazeGrid.appendChild(playerElement);
      console.log("Player element appended to maze grid.");
    }

    movePlayerElement(); // Set initial position visually
    console.log("Maze rendering complete.");
  }

  // --- Move Player Element (Visual Update) ---
  function movePlayerElement() {
    if (!playerElement) return; // Safety check

    const targetLeft = playerPos.x * cellSize;
    const targetTop = playerPos.y * cellSize;

    // *** UPDATED: Add log to confirm style application ***
    console.log(`Applying style - Top: ${targetTop}px, Left: ${targetLeft}px`);

    playerElement.style.left = `${targetLeft}px`;
    playerElement.style.top = `${targetTop}px`;

    // You can optionally force a reflow, though usually not needed with position changes
    // void playerElement.offsetWidth;
  }

  // --- Timer Functions (No changes) ---
  function startTimer() {
    if (timerInterval) clearInterval(timerInterval);
    startTime = Date.now();
    timerElement.textContent = "时间: 0s";
    timerInterval = setInterval(updateTimer, 1000);
  }
  function stopTimer() {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  function resetTimer() {
    stopTimer();
    timerElement.textContent = "时间: 0s";
    startTime = 0;
    firstMove = true;
  }
  function updateTimer() {
    const elapsed = Math.floor((Date.now() - startTime) / 1000);
    timerElement.textContent = `时间: ${elapsed}s`;
  }

  // --- Game Logic ---
  function initGame() {
    console.log("--- Initializing game ---");
    gameActive = false;
    resetTimer();
    const size = MIN_MAZE_SIZE + (currentLevel - 1) * LEVEL_INCREMENT;
    generateMaze(size, size);
    renderMaze(); // Render first

    gameActive = true; // Allow moves AFTER rendering

    // Focus handling (keep simplified version)
    if (
      document.activeElement &&
      typeof document.activeElement.blur === "function"
    ) {
      document.activeElement.blur();
    }
    document.body.focus(); // Try focusing body
    console.log(
      `Game initialized. Level ${currentLevel}. gameActive: ${gameActive}`
    );
  }

  // In maze.js
  function winGame() {
    console.log("--- Win Game ---"); // 确认获胜函数被调用
    gameActive = false;
    stopTimer();
    messageElement.textContent = "恭喜过关!";
    playSound(winSound);

    // *** 修复烟花效果 ***
    console.log("!!! WIN CONDITION MET - Attempting to start fireworks !!!");

    // 延迟启动烟花，确保DOM已经更新
    setTimeout(() => {
      if (typeof window.startFireworks === "function") {
        console.log("Calling startFireworks function...");
        window.startFireworks(); // 使用全局window对象访问函数
      } else {
        console.error(
          "ERROR: startFireworks function IS NOT DEFINED or accessible."
        );
        messageElement.textContent = "🎉 恭喜过关! (Fireworks Error) 🎉";
      }
    }, 100);
  }

  // --- Keyboard Input (Keep using e.code for reliability) ---
  function handleKeyPress(e) {
    // console.log(`Keydown: Code='${e.code}', ActiveElement=`, document.activeElement); // Keep for debugging if needed

    if (!gameActive) return;

    let dx = 0;
    let dy = 0;
    let validKey = false;

    switch (
      e.code // Using e.code
    ) {
      case "ArrowUp":
      case "KeyW":
        dy = -1;
        validKey = true;
        break;
      case "ArrowDown":
      case "KeyS":
        dy = 1;
        validKey = true;
        break;
      case "ArrowLeft":
      case "KeyA":
        dx = -1;
        validKey = true;
        break;
      case "ArrowRight":
      case "KeyD":
        dx = 1;
        validKey = true;
        break;
    }

    if (!validKey) return;
    e.preventDefault(); // Prevent scroll only for valid keys

    if (firstMove) {
      startTimer();
      firstMove = false;
    }

    const nextX = playerPos.x + dx;
    const nextY = playerPos.y + dy;

    if (
      nextX < 0 ||
      nextX >= cols ||
      nextY < 0 ||
      nextY >= rows ||
      maze[nextY][nextX] === WALL
    ) {
      // console.log("Invalid move (boundary or wall)."); // Optional log
      playSound(blockedSound);
      return; // Invalid move
    }

    // Valid move - Update state THEN visual
    console.log(
      `Moving player FROM (${playerPos.x}, ${playerPos.y}) TO (${nextX}, ${nextY})`
    );
    playerPos.x = nextX;
    playerPos.y = nextY;
    movePlayerElement(); // Call visual update
    playSound(moveSound);

    if (playerPos.x === endPos.x && playerPos.y === endPos.y) {
      winGame();
    }
  }

  // --- Event Listeners ---
  console.log("Setting up event listeners.");
  resetButton.addEventListener("click", () => {
    playSound(resetSound);
    initGame();
  });
  soundToggle.addEventListener("click", toggleSound);
  window.removeEventListener("keydown", handleKeyPress); // Ensure no duplicates
  window.addEventListener("keydown", handleKeyPress);
  console.log("Keydown listener attached to window.");

  // --- Initial Game Load ---
  createLevelButtons();
  initGame();

  // --- Window Resize Handling ---
  function handleResize() {
    if (gameActive) {
      renderMaze(); // Re-render to adapt to new window size
    }
  }

  // Add window resize listener
  window.addEventListener("resize", handleResize);
});
